package com.ljd.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.ljd.service.MsmService;
import com.why.handler.GuliException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class MsmServiceImpl implements MsmService {
    @Override
    public Boolean sendMsm(String code, String phone) {
        if(StringUtils.isEmpty(phone)){
            throw new GuliException(20001,"手机号为空");
        }
        Map<String, Object> sendCode = new HashMap<>();
        sendCode.put("code",code);
        DefaultProfile profile = DefaultProfile.getProfile("default", "LTAI5tJzgkguS3meWVnT6GB8", "MOJPqSozzPKHn3U1uCan1rrlCnyN9j");
        IAcsClient client = new DefaultAcsClient(profile);
        // 设置相关参数
        CommonRequest request = new CommonRequest();
        request.setSysMethod(MethodType.POST);
        request.setSysDomain("dysmsapi.aliyuncs.com");//短信服务的服务接入地址
        request.setSysVersion("2017-05-25");//API的版本号
        request.setSysAction("SendSms");//API的名称
        request.putQueryParameter("PhoneNumbers", phone);//接收短信的手机号码
        request.putQueryParameter("SignName", "阿里云短信测试");//短信签名名称
        request.putQueryParameter("TemplateCode", "SMS_154950909");//短信模板ID
        request.putQueryParameter("TemplateParam", JSONObject.toJSONString(sendCode));//短信模板变量对应的实际值
        try {
            CommonResponse response = client.getCommonResponse(request);
            boolean success = response.getHttpResponse().isSuccess();
            System.out.println(response.getData());
            return success;
        } catch (ServerException e) {
            e.printStackTrace();
            return false;
        } catch (ClientException e) {
            e.printStackTrace();
            return false;
        }

    }
}
